package com.example.codereview.editor;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.actionSystem.TypedAction;
import com.intellij.openapi.editor.actionSystem.TypedActionHandler;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;

/**
 * @author xianfeng
 * @date 2024/11/7 19:51
 * @description:
 */
public class EditorHandlerIllustration extends AnAction {

    static {
        EditorActionManager actionManager = EditorActionManager.getInstance();
        TypedAction typedAction = actionManager.getTypedAction();
        typedAction.setupHandler(new MyTypedHandler());
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        Editor editor = event.getData(CommonDataKeys.EDITOR);
        // Make sure at least one caret is available
        boolean menuAllowed = false;
        if (editor != null && project != null) {
            // Ensure the list of carets in the editor is not empty
            menuAllowed = !editor.getCaretModel().getAllCarets().isEmpty();
        }
        event.getPresentation().setEnabledAndVisible(menuAllowed);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Editor editor = event.getRequiredData(CommonDataKeys.EDITOR);
        EditorActionManager actionManager = EditorActionManager.getInstance();
        EditorActionHandler actionHandler =
                actionManager.getActionHandler(IdeActions.ACTION_EDITOR_CLONE_CARET_BELOW);
        actionHandler.execute(editor,
                editor.getCaretModel().getPrimaryCaret(), event.getDataContext());
    }

    public static final class MyTypedHandler implements TypedActionHandler {
        @Override
        public void execute(@NotNull Editor editor,
                            char c,
                            @NotNull DataContext dataContext) {
            Document document = editor.getDocument();
            Project project = editor.getProject();
            Runnable runnable = () -> document.insertString(0, "editor_basics\n");
            WriteCommandAction.runWriteCommandAction(project, runnable);
        }
    }
}
